package mspbots.next.ticket.core.grader.interceptor;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import mspbots.next.ticket.core.grader.AbstractGradeRuleAdapter;
import mspbots.next.ticket.core.grader.GradeRuleInterceptorRegistration;
import mspbots.next.ticket.core.points.PointResult;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Log4j2
@Service(value = "DUE_DATE_PASSED_POINT_RULE")
public class DueDatePassedRuleInterceptor extends AbstractGradeRuleAdapter {

    private static final String RULE_KEY = "DueDatePassed";
    private List<DueDatePassedParam> params;

    @Override
    public Mono<GradeRuleInterceptorRegistration> prepare(GradeRuleInterceptorRegistration gradeRuleInterceptorRegistration) {
        return Flux.just()
                .doFinally(r -> this.params = super.objectMapper
                        .convertValue(gradeRuleInterceptorRegistration.getRule().getParams(),
                                new TypeReference<>() {
                                }))
                .then(Mono.just(gradeRuleInterceptorRegistration));
    }

    @Override
    public Mono<PointResult> scoring(JsonNode ticket) {
        int point = 0;
        LocalDateTime requiredDate = super.getDateTimeValue(ticket.get("requiredDate"));
        if (!ObjectUtils.isEmpty(requiredDate)) {
            point = params.stream().filter(p -> p.isSelected()
                    && Duration.between(LocalDateTime.now(), requiredDate).isNegative())
                    .mapToInt(DueDatePassedParam::getPoints).sum();
        }
        return Mono.just(PointResult.withDefault().point(point)
                .detail(PointResult.Detail.with(point,
                        Map.of("requiredDate", ObjectUtils.isEmpty(requiredDate) ? "" : requiredDate), RULE_KEY)));
    }

    @Data
    private static class DueDatePassedParam {
        private Integer index;
        private Integer points;
        private String condition;
        private boolean selected;
    }
}
